/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.sjtu.bookread.Fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sackcentury.shinebuttonlib.ShineButton;
import com.sjtu.bookread.BookDetailActivity;
import com.sjtu.bookread.MainActivity;
import com.sjtu.bookread.R;
import com.sjtu.bookread.ReadPageActivity;
import com.sjtu.bookread.control.DatabaseControl;
import com.sjtu.bookread.myRecyclerview.MyRecyclerViewAdapter;
import com.sjtu.bookread.myRecyclerview.MyViewHolder;
import com.sjtu.bookread.obj.BookListObj;
import com.sjtu.bookread.obj.BookObj;
import com.sjtu.bookread.obj.BookObj1;
import com.sjtu.bookread.obj.CategoryObj;
import com.sjtu.bookread.service.BookService;
import com.sjtu.bookread.service.RecomService;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Demonstrates the use of {@link RecyclerView} with a {@link LinearLayoutManager}.
 */
public class RecomFragment extends Fragment {

    private static final String TAG = "RecomFragment";
    private static final String KEY_LAYOUT_MANAGER = "layoutManager";
    private static final int DATASET_COUNT = 6;

    private boolean isRanking = false;      //排行榜/具体分类
    private boolean isMale = true;         //男生/女生
    private String type = "hot";
    private String title = "玄幻";

    private enum LayoutManagerType {
        LINEAR_LAYOUT_MANAGER
    }

    protected LayoutManagerType mCurrentLayoutManagerType;
    private ProgressBar progressBar;
    private SwipeRefreshLayout swipeRefreshLayout;

    private long last_time = 0;
    private int last_book_id = -999;

    protected RecyclerView mRecyclerView;
    protected MyRecyclerViewAdapter<BookObj1> mAdapter;
    protected RecyclerView.LayoutManager mLayoutManager;
    protected List<BookObj1> bookObjList = new ArrayList<>();

    protected PagerSnapHelper snapHelper;

    RecomService recomService = RecomService.getRecomService();
    private Handler mHandler = new Handler(Looper.getMainLooper()); //获取主线程的Handler

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Initialize dataset, this data would usually come from a local content provider or
        // remote server.
        initDataset();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.recycler_view_frag, container, false);
        rootView.setTag(TAG);

        // BEGIN_INCLUDE(initializeRecyclerView)
        mRecyclerView = rootView.findViewById(R.id.recom_recyclerView);
        progressBar = rootView.findViewById(R.id.recom_progressBar);
        swipeRefreshLayout = rootView.findViewById(R.id.recom_swipeRefresh);

        // Set snapHelper
        snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(mRecyclerView);

        // LinearLayoutManager is used here, this will layout the elements in a similar fashion
        // to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
        // elements are laid out.
        mLayoutManager = new LinearLayoutManager(getActivity());

        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
        setRecyclerViewLayoutManager();

        mAdapter = new MyRecyclerViewAdapter<BookObj1>(getActivity(), R.layout.book_rec_item, bookObjList) {
            @Override
            public void convert(MyViewHolder holder, final BookObj1 BookObj) {
                if (last_book_id == -999) {
                    last_book_id = BookObj.getId();
                    last_time = System.currentTimeMillis();
                } else {
                    final long stay_time = System.currentTimeMillis() - last_time;

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d("submit_stay_time",String.valueOf(stay_time));
                            RecomService.getRecomService().submit_recom_stay(last_book_id,stay_time,MainActivity.ax,MainActivity.ay,MainActivity.az);
                        }
                    }).start();

                    last_time = System.currentTimeMillis();
                    last_book_id = BookObj.getId();
                }
                // 书名
                TextView bookName = holder.getView(R.id.rec_book_name);
                bookName.setText(BookObj.getTitle());
                // 封面 通过网络获取封面
                final ImageView imageView = holder.getView(R.id.rec_book_cover);
                final String iconURL = RecomService.ApiUrl + "/" + BookObj.getCover();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL url = new URL(iconURL);
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                            connection.setRequestMethod("GET");
                            connection.setConnectTimeout(10000);
                            if (connection.getResponseCode() == 200) {
                                InputStream inputStream = connection.getInputStream();
                                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        imageView.setImageBitmap(bitmap);
                                    }
                                });
                            }
                        } catch (Exception e) {
                            System.err.println(e.getMessage());
                        }
                    }
                }).start();
                // 作者
                TextView author = holder.getView(R.id.rec_book_author);
                author.setText(BookObj.getAuthor());
                // 简介
                TextView intro = holder.getView(R.id.rec_book_intro);
                String str = BookObj.getShortIntro();
                if (str.length() > 50) str = str.substring(0, 50);
                str += "...";
                intro.setText(str);
                //赞和踩
                ShineButton shineButton = holder.getView(R.id.recom_zan);
                shineButton.init(getActivity());
                shineButton.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(View view, boolean checked) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Log.d("submit_zan","1111111111111111111");
                                RecomService.getRecomService().submit_zan_cai(BookObj.getId(),1,MainActivity.ax,MainActivity.ay,MainActivity.az);
                            }
                        }).start();
                    }
                });

                final ImageButton imageButton = holder.getView(R.id.recom_cai);
                Drawable drawable = getResources().getDrawable(R.mipmap.cai);
                drawable.setBounds(0,0,70,70);
                imageButton.setImageDrawable(drawable);
                imageButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Drawable drawable = getResources().getDrawable(R.mipmap.cai_red);
                        drawable.setBounds(0,0,70,70);
                        imageButton.setImageDrawable(drawable);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Log.d("submit_cai","1111111111111111111");
                                RecomService.getRecomService().submit_zan_cai(BookObj.getId(),0,MainActivity.ax,MainActivity.ay,MainActivity.az);
                            }
                        }).start();
                    }
                });
            }
        };

        mAdapter.refresh(bookObjList);
        mAdapter.setOnItemClickListener(new MyRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(final int position) {
                Intent intent = new Intent(getActivity(), BookDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bookobj",bookObjList.get(position));
                intent.putExtras(bundle);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("submit_detail","11111111111111111111111");
                        RecomService.getRecomService().submit_in_detail(bookObjList.get(position).getId(),MainActivity.ax,MainActivity.ay,MainActivity.az);
                    }
                }).start();

                startActivity(intent);

            }

            @Override
            public void onLongClick(int position) {

            }
        });
        // Set CustomAdapter as the adapter for RecyclerView.
        mRecyclerView.setAdapter(mAdapter);
        // END_INCLUDE(initializeRecyclerView)

        //设置下拉显示的动画颜色
        swipeRefreshLayout.setColorSchemeColors(Color.RED, Color.BLUE);
        //下拉刷新的回调事件
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //数据刷新
                initDataset();
            }
        });

        return rootView;
    }

    /**
     * Set RecyclerView's LayoutManager to the one given.
     */
    public void setRecyclerViewLayoutManager() {
        mRecyclerView.setLayoutManager(mLayoutManager);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save currently selected layout manager.
        super.onSaveInstanceState(savedInstanceState);
    }

    /**
     * Generates Strings for RecyclerView's adapter. This data would usually come
     * from a local content provider or remote server.
     */
    private void initDataset() {
        bookObjList.clear();
        //检查网络连接
        ConnectivityManager connect = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connect.getActiveNetworkInfo();
        if (info == null || !info.isAvailable()) {
            Toast.makeText(getActivity(), "网络连接状况：未连接", Toast.LENGTH_LONG).show();
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                BookListObj bookListObj = recomService.getRecomBookList();
                if (bookListObj == null || bookListObj.isOk() == false) {
                    Looper.prepare();
                    Toast.makeText(getContext(), "获取数据失败", Toast.LENGTH_LONG).show();
                    Looper.loop();
                    return;
                }
                for (BookObj1 bookObj : bookListObj.getBooks()) {
                    bookObjList.add(bookObj);
                }
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.refresh(bookObjList);
                        progressBar.setVisibility(View.GONE);
                        //数据加载完毕时取消动画
                        swipeRefreshLayout.setRefreshing(false);
                        // Toast.makeText(getActivity(), "数据刷新完成", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();
    }
}
